package plus.easydo.rocketmq.config.producer;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 生产者配置
 * @author laoyu
 * @version 1.0
 * @date 2021/11/3
 */
@Configuration
@ConfigurationProperties(prefix = "rocketmq.producer")
public class ProducerConfigure {

    public static final Logger LOGGER = LoggerFactory.getLogger(ProducerConfigure.class);

    /**分组*/
    private String groupName;

    /**nameServer地址*/
    private String nameServerAddress;

    /**消息最大值*/
    private int maxMessageSize;

    /**消息发送超时时间*/
    private int sendMessageTimeOut;

    /**失败重试次数*/
    private int retryTimesWhenSendFailed;

    /**
     * 生产者配置
     *
     * @return org.apache.rocketmq.client.producer.DefaultMQProducer
     * @author laoyu
     * @date 2021/11/3
     */
    @Bean
    @ConditionalOnProperty(prefix = "rocketmq.producer", value = "enable", havingValue = "true")
    public DefaultMQProducer defaultProducer() throws MQClientException {
        LOGGER.info("---------------------------------------开始创建生产者---------------------------------------");
        DefaultMQProducer producer = new DefaultMQProducer(groupName);
        producer.setNamesrvAddr(nameServerAddress);
        producer.setVipChannelEnabled(false);
        producer.setMaxMessageSize(maxMessageSize);
        producer.setSendMsgTimeout(sendMessageTimeOut);
        producer.setRetryTimesWhenSendAsyncFailed(retryTimesWhenSendFailed);
        producer.start();
        LOGGER.info("--------------------------------------生产者创建成功---------------------------------------");
        return producer;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public String getNameServerAddress() {
        return nameServerAddress;
    }

    public void setNameServerAddress(String nameServerAddress) {
        this.nameServerAddress = nameServerAddress;
    }

    public int getMaxMessageSize() {
        return maxMessageSize;
    }

    public void setMaxMessageSize(int maxMessageSize) {
        this.maxMessageSize = maxMessageSize;
    }

    public int getSendMessageTimeOut() {
        return sendMessageTimeOut;
    }

    public void setSendMessageTimeOut(int sendMessageTimeOut) {
        this.sendMessageTimeOut = sendMessageTimeOut;
    }

    public int getRetryTimesWhenSendFailed() {
        return retryTimesWhenSendFailed;
    }

    public void setRetryTimesWhenSendFailed(int retryTimesWhenSendFailed) {
        this.retryTimesWhenSendFailed = retryTimesWhenSendFailed;
    }
}
